<?php
class OrdersController extends AppController {
    public $helpers = array('Html', 'Form','Session');
    public $components = array('Session','Auth','Cookie');
    public $uses=array('User','Order','Publicpage','Webhosting','Notification');

    public function index() {
        $userid= $this->Auth->User('id');
        $this->set('title_for_layout', 'Список заказов радиохостинга');
        $this->set('user_name_sidebar', AppController::getUserName($userid));
        $orders=$this->Order->findAllByUserid($userid);
        $this->set('orders', $orders);
        $webhosting_orders=$this->Webhosting->findAllByUserid($userid);
        $this->set('webhosting_orders', $webhosting_orders);
        $active_orders=0;
        $not_active_orders=0;
        $need_pay_orders=0;
        $all_orders_cost=0;
        $autocontinue_one_of=0;
        foreach($orders as $order)
        {
          $status=$order['Order']['status'];
          switch($status){
            case '0': $not_active_orders++; break;
            case '1': $need_pay_orders++; break;
            case '2': $active_orders++; break;
          }
          $all_orders_cost+=$order['Order']['cost'];
          if($order['Order']['autocontinue']==1)
            $autocontinue_one_of=1;
        }
        //webhost
        foreach($webhosting_orders as $order)
        {
          $status=$order['Webhosting']['status'];
          $all_orders_cost+=$order['Webhosting']['cost'];
          switch($status){
            case '0': $not_active_orders++; break;
            case '1': $need_pay_orders++; break;
            case '2': $active_orders++; break;
          }
        }
        $this->set('not_active_orders', $not_active_orders);
        $this->set('need_pay_orders', $need_pay_orders);
        $this->set('active_orders', $active_orders);
        $balancedata=AppController::getbalance($userid);
        $this->set('balance_value', $balancedata['balance']);
        $this->set('balance_time', $balancedata['time']);
        $this->set('all_orders_cost', $all_orders_cost);
        $need_money=$balancedata['balance']-$all_orders_cost;
        if($need_money<0)
            $this->set('need_money', -1*$need_money);
        else
            $this->set('need_money', $all_orders_cost);
        $this->set('autocontinue_one_of', $autocontinue_one_of);
        $user_data=$this->User->findById($userid);
        $user_login=$user_data['User']['login'];
        $this->set('user_login',$user_login);
    }
    public function add(){
      //$this->set('tarifs_data', $this->set_tarifs_data());
      $error=0;
      $errortxt='';
      //print_r($this->request->data);
      if ($this->request->is('post')) {

        $monthes=@$this->request->data['Order']['monthes'];
        unset($this->request->data['Order']['monthes']);
        $radiocost=@$this->request->data['Order']['cost'];
        $this->request->data['Order']['userid']=$this->Auth->User('id');
        $this->request->data['Order']['apassword']=AppController::EncryptPassword(@$this->request->data['Order']['apassword']);
        //if($this->request->data['Order']['radiohost']>0)
        $radiohost=$this->request->data['Order']['radiohost'];
        $webhost=$this->request->data['Order']['webhost'];
        if($radiohost>0)
        {
          unset($this->request->data['Order']['radiohost']);
          //Создаем заказ на радиохостинг
          $this->Order->create();
          if ($this->Order->save($this->request->data)) {
              //ОТПРАВКА МНЕ на ящик, что появился новый заказ
              $headers= "MIME-Version: 1.0\r\n";
              $headers .= "Content-type: text/html; charset=utf-8\r\n";
              $headers.="From: sale@radioheart.ru\r\n";
              $message="Новый заказ хостинга!";
              mail("germes.07@bk.ru", "RadioHeart - качественный радио хостинг",$message,$headers);
              $orid=$this->Order->getLastInsertID();
              $alias='/id'.$orid;
              //Добавляем в список публичных страниц
              $this->Order->query("INSERT INTO `public` (`id`, `orderid`, `nowair`, `stdesc`, `listen`, `site`, `descarea`, `logolnk`, `alias`) VALUES (NULL, '$orid', '0', '0', '0', '0', '', 'http://radioheart.ru/public/img/mystation_rh_logo.png', '$alias');");
              //$this->Order->query("INSERT INTO `publicpages` (`id`, `orderid`, `nowair`, `stdesc`, `listen`, `site`, `descarea`, `logolnk`, `alias`) VALUES (NULL, '$orid', '0', '0', '0', '0', '', 'http://radioheart.ru/public/img/mystation_rh_logo.png', '$alias');");
              SetCookie("radiohost_order_id",$orid,time()+604800,"/"); //куки на неделю
              /*Отправка письма пользователю о том, что он заказал хостинг*/
              $userid= $this->Auth->User('id');
              $user_data=$this->User->findById($userid);
              $user_email=$user_data['User']['email'];
              $message="
              Уважаемые клиент! Мы получили Ваш заказ на радио хостинг и готовы активировать Ваш аккаунт. Но сначала Вы должны оплатить услугу радио хостинга.<br>
              Сделать это можно перейдя по ссылке \"оплатить заказ\" в нашем биллинге <a href='http://radioheart.ru/billing/orders'>http://radioheart.ru/billing/orders</a>  (необходимо авторизоваться).<br>
              Спасибо за выбор нашего хостинга!<br>
              Администрация RadioHeart.ru
              ";
              mail($user_email, "RadioHeart - заказ радио хостинга",$message,$headers);

              //$this->Session->setFlash(__('The order has been saved'));
              //$this->redirect(array('action' => 'index'));
          } else {
              //$this->Session->setFlash(__('The order could not be saved. Please, try again.'));
              $errortxt='The order could not be saved. Please, try again.';
              $error=1;
          }
        }
      }
      //if($this->request->data['Order']['webhost']>0)
      $error_web=0;
      if($webhost>0)
      {
        unset($this->request->data['Order']['webhost']);
        $userid= $this->Auth->User('id');
        if ($this->request->is('post')) {
          $webhosting = $this->Webhosting->findByUserid($userid);
          if (!$webhosting) {
            $this->request->data['Webhosting']['userid']=$userid;
            $serverip="radioheart.ru";
            $this->request->data['Webhosting']['serverip']=$serverip;
            $this->request->data['Webhosting']['password']=AppController::EncryptPassword('myweborderpassword');
            //unset($this->request->data['Webhosting']['webpassword']);
            $this->request->data['Webhosting']['tarif']=$this->request->data['Order']['webtarif'];
            $webcost=$this->request->data['Webhosting']['cost']=$this->request->data['Order']['webcost'];
            $this->Webhosting->create();
            if ($this->Webhosting->save($this->request->data)) {
              //Отправить мне на мыло, что пришел новый заказ на экстре
              $headers= "MIME-Version: 1.0\r\n";
              $headers .= "Content-type: text/html; charset=utf-8\r\n";
              $headers.="From: extra@radioheart.ru\r\n";
              $message="Новый заказ web-хостинга!";
              mail("germes.07@bk.ru", "RadioHeart - качественный радио хостинг",$message,$headers);
              $user_data=$this->User->findById($userid);
              $user_email=$user_data['User']['email'];
              $message="Уважаемые клиент! Мы получили Ваш заказ на виртуальный хостинг и готовы активировать Ваш аккаунт. Для того, чтобы получить первый месяц пользования хостингом
                        абсолютно бесплатно, вам следует обратиться в тикеты с соответствующей просьбой.";
              mail($user_email, "RadioHeart - заказ радио хостинга",$message,$headers);
              SetCookie("webhost_order_id",$this->Webhosting->getInsertID(),time()+604800,"/"); //куки на неделю
              //$this->Session->setFlash(__('The weborder has been saved'));
              //$this->redirect(array('action' => 'index'));
            }
            else
            {
              $error_web=1;
              $errortxt='The web order could not be saved. Please, try again.';
            }
          }
          else
          {
            //$this->Session->setFlash(__('You already have webhosting'));
            //$this->redirect(array('action' => 'index'));
            $error_web=1;
            $errortxt='У вас уже есть виртуальный хостинг. Повторный заказ не требуется';
          }
        }
      }
      if(!$error)
      {
        //Все добавилось нормально, надо юзера отправить на пополнение баланса на нужную сумму
        $balancedata=AppController::getbalance($userid);
        $balance=$balancedata['balance'];
        $totalcost=@$radiocost+@$webcost;
        //делаем поправку на месяцы
        //$monthes=$_COOKIE['monthes'];
        //echo $monthes;
        if($monthes>1)
        {
          $totalcost=$totalcost*$monthes;
          switch($monthes)
          {
            case '1': $totalcost=$totalcost*1; break;
            case '2': $totalcost=$totalcost*1; break;
            case '3': $totalcost=$totalcost*0.95; break;
            case '4': $totalcost=$totalcost*0.95; break;
            case '5': $totalcost=$totalcost*0.95; break;
            case '6': $totalcost=$totalcost*0.9; break;
            case '7': $totalcost=$totalcost*0.9; break;
            case '8': $totalcost=$totalcost*0.9; break;
            case '9': $totalcost=$totalcost*0.9; break;
            case '10': $totalcost=$totalcost*0.9; break;
            case '11': $totalcost=$totalcost*0.9; break;
            case '12': $totalcost=$totalcost*0.85; break;
          }
        }
        else
        {
          $monthes=1;
        }
        if($totalcost<=$balance)//На балансе достаточно
        {
          //сразу проплачиваем
          if($radiohost>0)
          {
            //$orderid=$_COOKIE['radiohost_order_id'];
            $orderid=$this->Order->getInsertID();
            $this->pay($orderid,0,$monthes);
          }
          if(($webhost>0)&&(!$error_web))
          {
            //$orderid=$_COOKIE['webhost_order_id'];
            $orderid=$this->Webhosting->getInsertID();
            $this->payweborder($orderid,$monthes);
            //$this->Webhosting->pay($orderid);
            /*SetCookie("monthes","");
           $this->Cookie->delete('User.justregistered');
           $this->Cookie->delete('Order.steps');
           $this->redirect(array('controller'=>'webhosting','action' => 'pay',$orderid));   */
          }
          if($error_web && ($radiohost<1))
          {
            $this->Session->setFlash(__($errortxt));
             $this->redirect(array('controller'=>'orders','action' => 'index'));
          }
          /*SetCookie("monthes","",time()-3600,"/");
          SetCookie("radiohost_order_id","",time()-3600,"/");
          SetCookie("webhost_order_id","",time()-3600,"/");*/
          $this->Cookie->delete('User.justregistered');
          $this->Cookie->delete('Order.steps');
          //$this->redirect(array('controller'=>'orders','action' => 'index'));
          $this->redirect(array('controller'=>'orders','action' => 'setup'));
        }
        else  //не хватает на баласе
        {
          //вычисляем нужную сумму
          $needmoney= ($balance-$totalcost)*-1; //в месяц
          //Ставим куку, что юзер пришел после создания заказа
          $this->Cookie->write('Order.fromneworders', 1);
          //setcookie ("fromneworders", 1,time()+3600);
          // отправляем пополнять
          $this->redirect(array('controller'=>'users','action' => 'addcredits',$needmoney,'autosubmit'));

        }
        //$this->Session->setFlash(__('The order has been saved'));
        //$this->redirect(array('action' => 'index'));

      }
      else
      {
        $this->Session->setFlash(__($errortxt));
         $this->redirect(array('controller'=>'orders','action' => 'confirm'));
      }
    }
    public function payweborder($orderid=null,$monthes=null,$notpost=null){
      $userid= $this->Auth->User('id');
      if (!$orderid) {
            throw new NotFoundException(__('Invalid order id'));
      }
      $webhosting = $this->Webhosting->findById($orderid);
      $cost=$webhosting['Webhosting']['cost']; //Стоимость заказа в USD
      $opl=$webhosting['Webhosting']['oplachenodo'];
      $status=$webhosting['Webhosting']['status'];
      $webhosting['Webhosting']['tarif']=str_replace(" ","",$webhosting['Webhosting']['tarif']);
      $tarif=$webhosting['Webhosting']['tarif'];
      $password=$webhosting['Webhosting']['password'];
      $user_data=$this->User->findById($userid);
      $login=$user_data['User']['login'];
      $user_email=$user_data['User']['email'];
      $balance=$this->Order->query("SELECT `balance` FROM `balance` WHERE `userid`='$userid' LIMIT 1");
      $balance=$balance[0]['balance']['balance'];
      if(isset($monthes))
        $monthes=$monthes;
      else
        $monthes=@$this->request->data['Webhosting']['monthes'];
      if($monthes>1)
      {
        $cost=$cost*$monthes;
          switch($monthes)
          {
            case '1': $cost=$cost*1; break;
            case '2': $cost=$cost*1; break;
            case '3': $cost=$cost*0.95; break;
            case '4': $cost=$cost*0.95; break;
            case '5': $cost=$cost*0.95; break;
            case '6': $cost=$cost*0.9; break;
            case '7': $cost=$cost*0.9; break;
            case '8': $cost=$cost*0.9; break;
            case '9': $cost=$cost*0.9; break;
            case '10': $cost=$cost*0.9; break;
            case '11': $cost=$cost*0.9; break;
            case '12': $cost=$cost*0.85; break;
          }
      }
      if($cost<=$balance)//Средств достаточно
      {
        if ($this->request->is('post') || isset($notpost))  //юзер подтвердил оплату
        {
            date_default_timezone_set('Europe/Moscow');
            if($opl==0)//это первая оплата, создаем метку относительно текущей даты
            {
              $new_order_time=date("00:00 d.m.Y");
              $new_order_time=strtotime($new_order_time);
            }
            else
            {
              $new_order_time=$opl;
            }
            if($monthes>1)
                $new_order_time=$new_order_time+2592000*$monthes;
            else
                $new_order_time=$new_order_time+2592000;
            if($status==0)//Это новый заказ, не устанавливаем статус
            {
                $query="UPDATE `webhosting` SET `oplachenodo`='$new_order_time',`status`='0' WHERE `id`='$orderid'";
                $opl=$new_order_time;
                $this->Order->query($query);
                //Создаем юзера и активируем его
                //$tarif_tmp=str_replace(" ","",$tarif);
                if($this->create_user("root","2891eak",$login,$password,$password,$tarif))
                {
                  //Если все ништяк, юзер создался, ставим отметку, что заказ активировался
                  $query="UPDATE `webhosting` SET `status`='2' WHERE `id`='$orderid'";
                  $this->Order->query($query);
                }
            }
            else
            {
              if($monthes>1)
                $opl=$opl+2592000*$monthes;
              else
                $opl=$opl+2592000;
              $query="UPDATE `webhosting` SET `oplachenodo`='{$opl}',`status`='2' WHERE `id`='$orderid'";
              $this->Order->query($query);
              /*Activate user account*/
              $hid_user=strtolower($login);
              $root=$this->getRootLogin();
              $rootpass=$this->getRootPass();
              $this->activate_user_hid($root, $rootpass, $hid_user);
            }
            $query="UPDATE `balance` SET `balance`=`balance`-$cost WHERE `userid`='$userid'";
            $this->Order->query($query);
            $temp_data=date("d.m.Y",$opl);
            //echo "Заказ успешно оплачен до $temp_data";
            //if($status==0)
                //echo "<br />Спасибо за ваш заказ. Ваша оплата принята. Заказ будет активирован в ближайшем времени";
            //Отправить мне на мыло, что юзер проплатил заказ
            $headers= "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=utf-8\r\n";
            $headers.="From: extra@radioheart.ru\r\n";
            $message="Юзер ".$login." оплатил заказ web-хостинга ID ".$orderid;
            mail("germes.07@bk.ru", "RadioHeart - качественный радио хостинг",$message,$headers);
        }
      }
     /* else
      {
        $this->Session->setFlash(__('У вас недостаточно средств на балансе. Вам следует пополнить баланс.'));
        $this->redirect(array('controller' => 'users', 'action' => 'addcredits'));
      }
      //заполняем вывод для вьювера
      $this->set('orderid',$orderid);
      $this->set('balance',$balance);
      $this->set('cost',$cost);  */
    }
    public function confirm(){
      $this->autorender = false;
      $this->layout = false;
      $this->set('title_for_layout', 'Создание нового заказа');

        $bitrate=@$_COOKIE['bitrate'];
        if($bitrate>0)
            $this->set('radiohost',1);
        else
            $this->set('radiohost',0);
        $autodj=@$_COOKIE['autodj'];
        $usd=@$_COOKIE['cost'];
        $transcode=@$_COOKIE['reencode'];
        $crossfade=@$_COOKIE['crossfade'];
        $stat=@$_COOKIE['stat'];
        $listeners=@$_COOKIE['listeners'];
        $tarif_name='Radioheart '.@$listeners.' ('.@$bitrate.' кбит/с)';
        $rub=@$usd*34;

        //заполняем данные для вьювера
        $this->set('tarif',$tarif_name);
        $this->set('autodj',$autodj);

        if($transcode>0)
            $this->set('transcode',$transcode);
        else
            $this->set('transcode',0);
        if($crossfade>0)
            $this->set('crossfade',$crossfade);
        else
            $this->set('crossfade',0);
        if($stat==1)
            $this->set('stat',$stat);
        else
            $this->set('stat',0);
        //webhost
        $webhosting=$_COOKIE['webhost'];
        switch($webhosting)
        {
          case '1':$webhost_tarif='Extra 1';$webhost_cost=2;break;
          case '2':$webhost_tarif='Extra 2';$webhost_cost=6;break;
          case '3':$webhost_tarif='Extra 3';$webhost_cost=12;break;
        }
        $this->set('webhosting',$webhosting);
        $this->set('webhost_tarif',@$webhost_tarif);
        $this->set('webhost_cost',@$webhost_cost);
        $this->set('usd',$usd);
        $this->set('rub',$rub);
        $this->render('confirm');
     /* }
      else
      {
         $this->Session->setFlash(__($err));
         $this->redirect($this->referer());
      } */
    }
    public function set_tarifs_data(){
      $tarifs_data=$this->Order->query("SELECT `name` FROM `tarifs`");
      $tarifs_names=array();
      foreach ($tarifs_data as $tarif_item)
      {
        $tarifs_names[]= $tarif_item['tarifs']['name'];
      }
      return $tarifs_names;
    }
    public function discount($discount_type=null){
      if($discount_type>0)//юзер выбрал акцию для заказа
      {
        $this->set('whatwedo','show_order_form');
        $this->set('tarifs_data', $this->set_tarifs_data());
        switch($discount_type)
        {
          case 1: $name="Professional+"; $tarif_number=5; $autodjspace=10;$transcode=1;$stat=1; $cost=16; break;
          case 2: $name="Medium+"; $tarif_number=3; $autodjspace=5;$transcode=0;$stat=0;  $cost=8.8;  break;
          case 3: $name="Medium"; $tarif_number=2; $autodjspace=3;$transcode=0;$stat=0;  $cost=5.95; break;
          case 4: $name="Lite+"; $tarif_number=1; $autodjspace=3;$transcode=2;$stat=2;  $cost=4.5;  break;
          case 5: $name="Lite"; $tarif_number=0; $autodjspace=4;$transcode=2;$stat=2;  $cost=4.5;  break;
        }
        $this->set('tarif_number',$tarif_number);
        $this->set('autodjspace',$autodjspace);
        $this->set('cost',$cost);
      }
      else
      {
        $this->set('whatwedo','show_discounts');
      }
    }
    public function save()
    {
      if ($this->request->is('post') || $this->request->is('put')) {
        //print_r($this->request->data);
        $id=$this->request->data['Order']['id'];
        $order = $this->Order->findById($id);
        $this->Order->id = $id;
        $ftppass_unencrypted=@$this->request->data['Order']['ftppassword'];
        $atodjpassword_unencrypted=@$this->request->data['Order']['apassword'];
        $icecastpassword_unencrypted=@$this->request->data['Order']['icecastpassword'];
        $this->request->data['Order']['apassword']=AppController::EncryptPassword(@$this->request->data['Order']['apassword']);
        $this->request->data['Order']['icecastpassword']=AppController::EncryptPassword(@$this->request->data['Order']['icecastpassword']);
        $this->request->data['Order']['ftppassword']=AppController::EncryptPassword(@$this->request->data['Order']['ftppassword']);
        $error=0;
        $error_txt='';
        //Проверяем пароли, если они не совпадают, значит пароль изменен, следовательно, надо его тоже изменить
        if($this->request->data['Order']['apassword']!=$order['Order']['apassword'])
        {
          //изменяем пароль автодиджея
          $serverip=$order['Order']['serverip'];
          $port=$order['Order']['port'];
          $status='1';
          $atodjpassword=$atodjpassword_unencrypted;
          $action='edit';
          $url='http://'.$serverip.'/panel/usersedit.php?action='.$action.'&login=user'.$port.'&password='.$atodjpassword.'&status='.$status;
          //$url="http://s1.radioheart.ru/panel/usersedit.php?action=edit&login=user8000&password=ultradio222&status=1";
          $ch = curl_init();
             //GET запрос указывается в строке URL
            curl_setopt($ch, CURLOPT_URL,$url);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($ch, CURLOPT_USERAGENT, 'SunEngine');
            $data = curl_exec($ch);
            curl_close($ch);
            //echo iconv("utf-8", "windows-1251",$data);
            if(strpos($data,"Пользователь успешно отредактирован")===false)
            {
              $error=1;
              $error_txt+='Пароль от Автодиджея НЕ изменен<br>';
            }
        }
        if($this->request->data['Order']['icecastpassword']!=$order['Order']['icecastpassword'])
        {
          //изменяем пароль icecast
          $ip=$serverip=$order['Order']['serverip'];
          $port=$order['Order']['port'];
          if(($ip=="s1.radioheart.ru")&&($port=='8001'))
          {}
          else
          {
            //получаем старый пароль для str_replace в дальнейшем
              if($ip=="s1.radioheart.ru")
                  $config_file="/var/www/user$port/confs/icecast.xml";
              else
                  $config_file="http://$ip/user$port/confs/icecast.xml";
              $xml=array();
              $tt=array();
              $xml = simplexml_load_file($config_file);
              foreach($xml->mount as $mm)
              {
                if($mm->password!="nonstop")
                {
                  $old_pass=$mm->password;  //нашли старый пароль
                }
              }
              $new_pass=$icecastpassword_unencrypted;
              if($serverip=="s1.radioheart.ru")
                  $config_file="/var/www/user$port/confs/icecast.xml";
              else
                  $config_file="http://$serverip/user$port/confs/icecast.xml";
              $icecastconfigcontent=file_get_contents($config_file);
              $icecastconfigcontent=str_replace($old_pass,$new_pass,$icecastconfigcontent);

              $url='http://'.$serverip.'/panel/usericecastconf.php';
              $postdata='username=user'.$port.'&icecastconfigcontent='.$icecastconfigcontent;
              if(AppController::_is_curl_installed())
              {
                  $data= $this->post_content($url,$postdata);
                  //echo iconv("utf-8", "windows-1251",$data);
                  //echo $data;
              }
            }
        }

        if($this->request->data['Order']['ftppassword']!=$order['Order']['ftppassword'])
        {
          //изменяем пароль ftp
          $serverip=$order['Order']['serverip'];
          $port=$order['Order']['port'];
          $ftppass=$ftppass_unencrypted;
          $url='http://'.$serverip.'/panel/userpassword.php?username=user'.$port.'&passwd='.$ftppass."&pwdchange";
          //$url="http://s1.radioheart.ru/panel/usersedit.php?action=edit&login=user8000&password=ultradio222&status=1";
          $ch = curl_init();
             //GET запрос указывается в строке URL
            curl_setopt($ch, CURLOPT_URL,$url);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($ch, CURLOPT_USERAGENT, 'SunEngine');
            $data = curl_exec($ch);
            curl_close($ch);
            //echo iconv("utf-8", "windows-1251",$data);
            //echo $data;
            if(strpos($data,"password updated successfully")===false)
            {
              $error=1;
              $error_txt+='Пароль от FTP НЕ изменен <br>';
            }
        }
        if(!$error)
        {
          if ($this->Order->save($this->request->data)) {
              $this->Session->setFlash(__('Параметры заказа обновлены.'));
              $this->redirect(array('action' => 'index'));
          } else {
              $this->Session->setFlash(__('Unable to update your order.'));
          }
        }
        else
        {
          $this->Session->setFlash(__($error_txt));
          $this->redirect(array('action' => 'index'));
        }
      }
    }
    public function pay($orderid = null,$redirect=1,$monthes=null,$notpost=null){
      $userid= $this->Auth->User('id');
      if (!$orderid) {
            throw new NotFoundException(__('Invalid order id'));
      }
      $order = $this->Order->findById($orderid);
      $cost=$order['Order']['cost']; //Стоимость заказа в USD
      $opl=$order['Order']['oplachenodo'];
      $status=$order['Order']['status'];
      $port=$order['Order']['port'];
      $serverip=$order['Order']['serverip'];
      $balance=$this->Order->query("SELECT `balance` FROM `balance` WHERE `userid`='$userid' LIMIT 1");
      $balance=@$balance[0]['balance']['balance'];
      if(isset($monthes))
        $monthes=$monthes;
      else
        $monthes=@$this->request->data['Order']['monthes'];
      if($monthes>1)
      {
        $cost=$cost*$monthes;
        switch($monthes)
          {
            case '1': $cost=$cost*1; break;
            case '2': $cost=$cost*1; break;
            case '3': $cost=$cost*0.95; break;
            case '4': $cost=$cost*0.95; break;
            case '5': $cost=$cost*0.95; break;
            case '6': $cost=$cost*0.9; break;
            case '7': $cost=$cost*0.9; break;
            case '8': $cost=$cost*0.9; break;
            case '9': $cost=$cost*0.9; break;
            case '10': $cost=$cost*0.9; break;
            case '11': $cost=$cost*0.9; break;
            case '12': $cost=$cost*0.85; break;
          }
      }
      if($cost<=$balance)//Средств достаточно
      {
        if ($this->request->is('post')||isset($notpost))  //юзер подтвердил оплату
        {
          date_default_timezone_set('Europe/Moscow');
          if($status==0)//Это новый заказ, не устанавливаем статус
          {
            if($opl==0)//первая оплата заказа, надо сгенерировать время относително текущей даты
            {
              $new_order_time=date("00:00 d.m.Y");
              $new_order_time=strtotime($new_order_time);
            }
            else
            {
              $new_order_time=$opl;
            }
              //Делаем поправку на месяцы
              if($monthes>1)
              {
                $new_order_time=$new_order_time+2592000*$monthes;
              }
              else
              {
                $new_order_time=$new_order_time+2592000;
              }
              $query="UPDATE `orders` SET `oplachenodo`='$new_order_time',`status`='0' WHERE `id`='$orderid'";
              //Ставим правильную дату
              $opl=$new_order_time;
          }
          else
          {
            //Делаем поправку на месяцы
            if($monthes>1)
              $opl=$opl+2592000*$monthes;
            else
              $opl=$opl+2592000;
            $query="UPDATE `orders` SET `oplachenodo`='{$opl}',`status`='2' WHERE `id`='$orderid'";
          }
          $this->Order->query($query);
          $query="UPDATE `balance` SET `balance`=`balance`-$cost WHERE `userid`='$userid'";
          $this->Order->query($query);
          $order_pay_time=date("d.m.Y",$opl);
          if($status==0)
          {
            $message_to_user="<br />Спасибо за ваш заказ. Ваша оплата принята. Заказ будет активирован в ближайшем времени";
          }
          else
          {
            //Продление заказа, надо бы убрать напоминалку с главной стр. биллинга и изменить ей кружек
            $query="UPDATE `notifications` SET `onmain`='0',`type`='grey' WHERE `userid`='{$userid}' AND `orderid`='{$orderid}'";
            $this->Order->query($query);
          }
          //Отправить мне на мыло, что юзер проплатил заказ
          $user_data=$this->User->findById($userid);
          $user_login=$user_data['User']['login'];
          $headers= "MIME-Version: 1.0\r\n";
          $headers .= "Content-type: text/html; charset=utf-8\r\n";
          $headers.="From: sale@radioheart.ru\r\n";
          $message="Юзер ".$user_login." оплатил заказ ID ".$orderid;
          mail("germes.07@bk.ru", "RadioHeart - качественный радио хостинг",$message,$headers);
          if($status>0)
          {
            if (AppController::_is_curl_installed()) {
              //Enabling icecast
              $action="enable";
              $url='http://'.$serverip.'/panel/usericecast.php?action='.$action.'&port='.$port;
              $ch = curl_init();
               //GET запрос указывается в строке URL
              curl_setopt($ch, CURLOPT_URL,$url);
              curl_setopt($ch, CURLOPT_HEADER, false);
              curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
              curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
              curl_setopt($ch, CURLOPT_USERAGENT, 'SunEngine');
              $data = curl_exec($ch);
              curl_close($ch);
              //enabling cronjob
              $url='http://'.$serverip.'/panel/usercron.php?action='.$action.'&port='.$port;
              $ch = curl_init();
                 //GET запрос указывается в строке URL
                curl_setopt($ch, CURLOPT_URL,$url);
                curl_setopt($ch, CURLOPT_HEADER, false);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
                curl_setopt($ch, CURLOPT_USERAGENT, 'SunEngine');
                $data = curl_exec($ch);
                curl_close($ch);
            }
           }
           //флешка и редирект
           //if(!isset($_COOKIE['radiohost_order_id']))
           if($redirect==1)
           {
             $this->Session->setFlash(__('Заказ был успешно оплачен.'));
             $this->redirect(array('action' => 'index'));
           }
        }
      }
      else
      {
         $needmoney= ($balance-$cost)*-1;
         $this->Session->setFlash(__('У вас недостаточно средств на балансе. Вам следует пополнить баланс.'));
         $this->redirect(array('controller' => 'users', 'action' => 'addcredits',$needmoney));
      }
      //print_r($balance);
      //заполняем вывод для вьювера
      $this->set('orderid',$orderid);
      $this->set('balance',$balance);
      $this->set('cost',$cost);
    }
    public function changeicecastpassword($orderid=null){
      if ($this->request->is('post'))
      {
        $serverip=$this->request->data['Order']['ip'];
        $port=$this->request->data['Order']['port'];
        $new_pass=$this->request->data['Order']['new_pass'];
        $old_pass=$this->request->data['Order']['old_pass'];
        if($serverip=="s1.radioheart.ru")
            $config_file="/var/www/user$port/confs/icecast.xml";
        else
            $config_file="http://$serverip/user$port/confs/icecast.xml";
        $icecastconfigcontent=file_get_contents($config_file);
        $icecastconfigcontent=str_replace($old_pass,$new_pass,$icecastconfigcontent);

        $url='http://'.$serverip.'/panel/usericecastconf.php';
        $postdata='username=user'.$port.'&icecastconfigcontent='.$icecastconfigcontent;
        if(AppController::_is_curl_installed())
        {
            $data= $this->post_content($url,$postdata);
            //echo iconv("utf-8", "windows-1251",$data);
            //echo $data;
            $this->Session->setFlash(__('Ваш пароль был изменен на '.$new_pass));
        }
        $this->Session->setFlash(__('Ваш пароль НЕ был изменен'));
        $this->redirect(array('action' => 'index'));
      }
      else
      {
        $order = $this->Order->findById($orderid);
        $ip=$order['Order']['serverip'];
        $port=$order['Order']['port'];
        if($ip=='s1.radioheart.ru' and ($port==8001))
        {
          $this->Session->setFlash(__('К сожалению, изменение пароля в автоматическом режиме невозможно. Обратитесь в тикеты'));
          $this->redirect(array('action' => 'index'));
        }
        else
        {
            //получаем старый пароль для str_replace в дальнейшем
            if($ip=="s1.radioheart.ru")
                $config_file="/var/www/user$port/confs/icecast.xml";
            else
                $config_file="http://$ip/user$port/confs/icecast.xml";
            $xml=array();
            $tt=array();
            $xml = simplexml_load_file($config_file);
            foreach($xml->mount as $mm)
            {
              if($mm->password!="nonstop")
              {
                $old_pass=$mm->password;
              }
            }
            $this->set('orderid',$orderid);
            $this->set('old_pass',$old_pass);
            $this->set('ip',$ip);
            $this->set('port',$port);
        }
      }
    }
    public function constructor($orderid=null){
      $userid= $this->Auth->User('id');
        $this->set('title_for_layout', 'Конструктор скриптов');
        $this->set('user_name_sidebar', AppController::getUserName($userid));
        if ($this->request->is('post'))
        {
          $this->set('whatwedo','showscript');
          $this->set('selected_data',$this->request->data);
          $this->set('isuserhaveorders',1);
        }
        else
        {
          $this->set('whatwedo','showform');
          $orders=$this->Order->findAllByUseridAndStatus($userid,2);
          if($orders)
          {
            $streams=array();
            foreach ($orders as $order)
            {
              $streams[]="http://".$order['Order']['serverip'].":".$order['Order']['port'].$order['Order']['mount'];
            }
            $this->set('isuserhaveorders',1);
          }
          else
          {
            $this->set('isuserhaveorders',0);
          }
          $this->set('streams',@$streams);
        }
    }
    public function api(){
      $userid= $this->Auth->User('id');
        $this->set('title_for_layout', 'Приложения');
        $this->set('user_name_sidebar', AppController::getUserName($userid));
      if ($this->request->is('post'))
      {
        $this->set('isuserhaveorders',1);
        $this->set('whatwedo','showscript');
        $orderid=$this->request->data['Order']['orderid'];
        $order = $this->Order->findById($orderid);
        $autodjlink="http://".$order['Order']['serverip']."/panel";
        $autodjport=$order['Order']['port'];
        $this->set('autodjlink',$autodjlink);
        $this->set('autodjport',$autodjport);
        $this->set('server',$order['Order']['serverip']);
        $this->set('port',$autodjport);
      }
      else
      {
        $this->set('whatwedo','showform');
        $orders=$this->Order->findAllByUseridAndStatus($userid,2);
        if($orders)
        {
          $streams=array();
          $orders_ids=array();
          foreach ($orders as $order)
          {
            if($order['Order']['autodjspace']>0){
              $streams[]="http://".$order['Order']['serverip'].":".$order['Order']['port'].$order['Order']['mount'];
              $orders_ids[]= $order['Order']['id'];
            }
          }
          $this->set('streams',$streams);
          $this->set('orders_ids',$orders_ids);
          $this->set('isuserhaveorders',1);
        }
        else
        {
          $this->set('isuserhaveorders',0);
        }
      }
    }
    public function player()
    {
      $userid= $this->Auth->User('id');
      $this->set('title_for_layout', 'Плеера');
      $this->set('user_name_sidebar', AppController::getUserName($userid));
      $orders=$this->Order->findAllByUseridAndStatus($userid,2);
      if($orders)
        $this->set('isuserhaveorders',1);
      else
        $this->set('isuserhaveorders',0);
    }
    public function post_content ($url,$postdata) {
        $uagent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)";

        $ch = curl_init( $url );
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_ENCODING, "");
        curl_setopt($ch, CURLOPT_USERAGENT, $uagent);  // useragent
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        $content = curl_exec( $ch );
        curl_close( $ch );
        return $content;
    }
    public function neworder()
    {
      $this->autorender = false;
      $this->layout = false;
      $this->set('title_for_layout', 'Шаг 2 - Заказ');
      $this->Cookie->write('Order.steps', 'true',false,3600);
      //очишаем куки от прошлых заказов
      SetCookie("radiohost_order_id","",time()-3600,"/");
      SetCookie("webhost_order_id","",time()-3600,"/");
      SetCookie("monthes","",time()-3600,"/");
      $this->render('neworder');
    }
    public function setup($tosetup=null){
      $this->autorender = false;
      $this->layout = false;
      if(isset($tosetup))  //возвращает из оплаты
      {
        $monthes=$_COOKIE['monthes'];
        //$monthes=1;
        //print_r($_COOKIE);
        if(isset($_COOKIE['radiohost_order_id']))
        {
            $radiohost_order_id=$_COOKIE['radiohost_order_id'];
            $this->pay($radiohost_order_id,0,$monthes,'notpost');
        }
        if(isset($_COOKIE['webhost_order_id']))
        {
          $webhost_order_id=$_COOKIE['webhost_order_id'];
          $this->payweborder($webhost_order_id,$monthes,'notpost');
        }
        goto tosetup;
      }
      if ($this->request->is('post') || $this->request->is('put')) {
        $error=0;
        /*echo '<pre>';
        print_r($this->request->data);
        echo '</pre>'; */
        $id=@$this->request->data['Order']['id'];
        $radiohost=@$this->request->data['Order']['radiohost'];
        $webhost=@$this->request->data['Order']['webhost'];
        $webhost_id= @$this->request->data['Order']['id_web'];
        $webhost_pass= @$this->request->data['Order']['password_web'];
        $webhost_oplachenodo= @$this->request->data['Order']['webhost_oplachenodo'];
        if($radiohost==1)
        {
          //$this->request->data['Order']['apassword']=AppController::EncryptPassword($this->request->data['Order']['apassword']);
          $order = $this->Order->findById($id);
          $order['Order']['apassword']=AppController::EncryptPassword($this->request->data['Order']['apassword']);
          $order['Order']['mount']=$this->request->data['Order']['mount'] ;
          $order['Order']['stationname']= $this->request->data['Order']['stationname'] ;
          $order['Order']['stationsite']= $this->request->data['Order']['stationsite'] ;
          /*$new_order_time=date("00:00 d.m.Y");
          $new_order_time=strtotime($new_order_time);
          $new_order_time=$new_order_time+2592000*$monthes;*/
          $order['Order']['oplachenodo']=$this->request->data['Order']['oplachenodo'];
          $this->Order->id = $id;
          if ($this->Order->save($order)) {
              $this->Session->setFlash(__('Параметры заказа обновлены.'));
              //$this->redirect(array('action' => 'index'));
          } else {
              $this->Session->setFlash(__('Unable to update your order.'));
              $error=1;
          }
        }
        if($webhost==1)
        {
          $id=$webhost_id;
          $order = $this->Webhosting->findById($id);
          $order['Webhosting']['password']=AppController::EncryptPassword($webhost_pass);
          /*$new_order_time=date("00:00 d.m.Y");
          $new_order_time=strtotime($new_order_time);
          $new_order_time=$new_order_time+2592000*$monthes; */
          $order['Webhosting']['oplachenodo']=$webhost_oplachenodo;
          $this->Webhosting->id = $id;
          if ($this->Webhosting->save($order)) {
              $this->Session->setFlash(__('Параметры заказа обновлены.'));
              //$this->redirect(array('controller'=>'orders','action' => 'index'));
          } else {
              $this->Session->setFlash(__('Unable to update your order.'));
              $error=1;
          }
        }
        if(!$error)
        {
          SetCookie("monthes","",time()-3600,"/");
          SetCookie("radiohost_order_id","",time()-3600,"/");
          SetCookie("webhost_order_id","",time()-3600,"/");
          $this->redirect(array('controller'=>'orders','action' => 'done'));
        }
      }
      else
      {
        tosetup:
        if(isset($_COOKIE['radiohost_order_id']))
        {
          $radiohost_order_id=$_COOKIE['radiohost_order_id'];
          $radiohost=1;
          $tmp=$this->Order->findById($radiohost_order_id);
          $oplachenodo=$tmp['Order']['oplachenodo'];
          $this->set('oplachenodo',$oplachenodo);
        }
        else
        {
          $radiohost=0;
        }
        if(isset($_COOKIE['webhost_order_id']))
        {
          $webhost_order_id=$_COOKIE['webhost_order_id'];
          $webhost=1;
          $tmp=$this->Webhosting->findById($webhost_order_id);
          $webhost_oplachenodo=$tmp['Webhosting']['oplachenodo'];
          $this->set('webhost_oplachenodo',$webhost_oplachenodo);
        }
        else
        {
          $webhost=0;
        }
        $this->set('radiohost',$radiohost);
        $this->set('webhost',$webhost);
        $this->set('radiohost_order_id',@$radiohost_order_id);
        if(isset($webhost_order_id))
            $this->set('webhost_order_id',$webhost_order_id);
      }
      $this->render('setup');
    }
    public function done()
    {
      $this->autorender = false;
      $this->layout = false;
      /*echo '<pre>';
      print_r($this->request->data);
      echo '</pre>'; */
      $this->render('done');
    }
        public function getRootLogin()
    {
      return "root";
    }
    public function getRootPass()
    {
      return "2891eak";
    }
    public function activate_user_hid($root, $rootpass, $hid_user){
    $url = "https://".$_SERVER['SERVER_NAME']."/manager/ispmgr?authinfo=".$root.":".$rootpass."&out=xml&func=user.enable";
    $delete_user_hid["elid"] = $hid_user;
     foreach( $delete_user_hid as $k => $v )
       {
         $url .= '&'.$k.'='.urlencode($v);
     }
    // echo $url;
    // exit();
      if(AppController::_is_curl_installed())
      {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Get the response and close the channel.
        $response = curl_exec($ch);
        curl_close($ch);
        echo $response;
      }
    }
    function create_user($root, $rootpass,$name,$passwd,$confirm,$preset){
     if(AppController::_is_curl_installed())
     {
        $url = "http://".$_SERVER['SERVER_NAME']."/manager/ispmgr?authinfo=".$root.":".$rootpass."&out=xml&func=user.edit&sok=yes&name=$name&passwd=$passwd&confirm=$confirm&preset=$preset";
        //echo $url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Get the response and close the channel.
        $response = curl_exec($ch);
        echo $response;
        curl_close($ch);
        $findme="<doc><ok/></doc>";
        $pos = strpos($response, $findme);
        if($pos === false)
        {
          return 0;
        }
        else
        {
          return 1;
        }
      }
  }
}

?>